<?php

// 发送短信码
// POST sms.sendCode

namespace app\api\resource\sms;
use think\Db;
use app\common\validate\Member as MemberValidate;
use app\common\lib\SmsCode as SmsCodeCommonLib;
use app\common\lib\Yp as YpCommonLib;

class SendCode
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '发送短信码';
    // 参数
    public $_param  = [
        'mobile' => '手机号',
    ];

    public function run(&$request)
    {
        $params   = $request->param();
        $validate = new MemberValidate;
        if ( !$validate->scene('sendCode')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $ret = Db::name('member')->where('mobile',$params['mobile'])->value('id');
        if ( !is_null($ret) ) return [400,'该手机号已被注册'];

        $mobile = $params['mobile'];
        $code   = rand(100000,999999);

        $yp  = new YpCommonLib;
        $res = $yp->sendCode($mobile,$code);
        if (0 == $res['code']) {
            $alias = 'reg';
            $bool  = SmsCodeCommonLib::write($mobile,$alias,$code);
            if ($bool) {
                $msg = '短信码已发送';
                return [201,$msg];
            } else {
                $msg = '2次发送间隔必须大于60秒';
                return [400,$msg];
            }
        } else {
            return [400,'短信系统异常'];
        }
    }
}